#This file is part of kazami.
#
#    kazami is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    kazami is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with kazami.  If not, see <http://www.gnu.org/licenses/>.

from board import Board

class Referee(object):
    
    DIRECTIONS = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
    DRAW = "D"
    
    def __init__(self):
        self.board = Board()
        self.turn = Board.BLACK
        self.opponent = Board.WHITE
        self.ongoing = True
        self.black = 2
        self.white = 2
        self.moves = dict()
        self.ai = None
    
    def flip(self, row, column):
        cur = self.board.get(row, column)
        if cur == Board.BLACK:
            self.board.set(row, column, Board.WHITE)
        elif cur == Board.WHITE:
            self.board.set(row, column, Board.BLACK)
    
    def inspect_move(self, row, column):
        for direction in Referee.DIRECTIONS:
            rcur = row + direction[0]
            ccur = column + direction[1]
            targets = []
            while rcur >= 0 and ccur >= 0 and rcur < Board.NUMROWS and ccur < Board.NUMCOLS:
                cur = self.board.get(rcur, ccur)
                if cur == self.opponent:
                    targets.append((rcur,ccur))
                elif cur == self.turn and len(targets)>0:
                    self.moves[(row,column)] = targets
                    break
                else:
                    break
                rcur += direction[0]
                ccur += direction[1]
    
    def legal_moves(self):
        self.moves = dict()
        for row in range(0, Board.NUMROWS):
            for col in range(0, Board.NUMCOLS):
                if self.board.get(row, col) == Board.EMPTY:
                    self.inspect_move(row, col)
        return self.moves
    
    def make_move(self, move):
        if move in self.moves.keys():
            self.board.set(move[0],move[1],self.turn)
            for target in self.moves[move]:
                self.flip(target[0],target[1])
            self.turn, self.opponent = self.opponent, self.turn
        if len(self.legal_moves()) == 0:
            self.turn, self.opponent = self.opponent, self.turn
        if self.turn == Board.WHITE and self.ai != None:
            self.make_move(self.ai.pick_move(self.legal_moves()))
        return self.legal_moves()
    
    def plug_ai(self, ai):
        self.ai = ai